package com.vichat.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.business.entity.VcAlarm;
import com.vichat.business.service.IVcAlarmService;
import com.vichat.business.thread.AlarmSendThread;
import com.vichat.business.vo.AlarmVO;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.util.AES;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.util.StringToPropertiesConverter;
import com.vichat.common.vo.Json;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.service.IRoomService;
import com.vichat.room.vo.RoomVO;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.entity.UserPartyCompany;
import com.vichat.user.service.IUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ranjx on 2017/11/20.
 */
@Controller
@RequestMapping("/warnApi")
public class AlarmApiController {
    private static Logger logger = LoggerFactory.getLogger(AlarmApiController.class);
    ExecutorService tp = Executors.newCachedThreadPool();
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IVcAlarmService vcAlarmService;


    /**
     * 创建告警
     *
     * @return
     */
    @RequestMapping("/alarm")
    @ResponseBody
    public Json alarm(@RequestBody AlarmVO alarmVO) {
        Json json = new Json();
        try {
            boolean isAlarm = false;

            logger.info(JSONObject.toJSONString(alarmVO));
            String token = AES.decrypt(alarmVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(alarmVO.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(alarmVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }
            UserPartyCompany userPartyCompany = userService.getUserPartyCompanyByPartyId(userBasicFDB.getPartyId());
            if(userPartyCompany == null){
                throw new Exception("Party Data Error");
            }
            String companyFun = userPartyCompany.getFunction();
            if(StringUtils.isNotBlank(companyFun)) {
                if (companyFun.substring(0, 1).equals("1")) {
                    isAlarm = true;
                }
            }

            if(isAlarm) {
                VcAlarm queryBean = null;
                if (NumberUtils.isNotNullOrZero(alarmVO.getAlarmId())) {
                    queryBean = vcAlarmService.getAlarmByalarmId(alarmVO.getAlarmId(), 1L);
                } else if (NumberUtils.isNotNullOrZero(alarmVO.getUid())) {
                    queryBean = vcAlarmService.getAlarmByUid(alarmVO.getUid(), 1L);
                }

                if (queryBean == null) {
                    List<UserBasic> userBasicListFDB = userService.getUserBasicsByOrgId(userBasicFDB.getOrgId());
                    //创建临时频道
                    RoomBasic roomBasic = createRoom(userBasicListFDB, userBasicFDB, alarmVO);
                    //创建告警
                    VcAlarm alarm = vcAlarmService.saveAlarm(convertAlarm(roomBasic, alarmVO));

                    tp.execute(new AlarmSendThread(roomService, roomBasic.getRid(), GlobalConstant.IMS_ALARM, alarm));
                } else {
                    if (StringUtils.isNotBlank(alarmVO.getLongitude()) && StringUtils.isNotBlank(alarmVO.getLatitude()) && alarmVO.getLocTime() > queryBean.getLocTime()) {
                        queryBean.setLongitude(alarmVO.getLongitude());
                        queryBean.setLatitude(alarmVO.getLatitude());
                        queryBean.setAddress(alarmVO.getAddress());
                        queryBean.setPreCision(alarmVO.getPreCision());
                        queryBean.setLocType(alarmVO.getLocType());
                        queryBean.setLocTime(alarmVO.getLocTime());
                        queryBean.setAlarmType(alarmVO.getAlarmType());
                        queryBean = vcAlarmService.saveAlarm(queryBean);
                    }
                }
                json.setObj(queryBean);
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 查询告警信息
     *
     * @return
     */
    @RequestMapping("/getAlarms")
    @ResponseBody
    public Json getAlarms(@RequestBody AlarmVO alarmVO) {
        Json json = new Json();
        try {
            String token = AES.decrypt(alarmVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(alarmVO.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(alarmVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            List<VcAlarm> vcAlarmFDB = vcAlarmService.queryAlarmsByOrgId(userBasicFDB.getOrgId());
            json.setObj(vcAlarmFDB);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 关闭告警
     *
     * @return
     */
    @RequestMapping("/finishAlarm")
    @ResponseBody
    public Json finishAlarm(@RequestBody AlarmVO alarmVO) {
        Json json = new Json();
        try {
            String token = AES.decrypt(alarmVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(alarmVO.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(alarmVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            VcAlarm queryBean = null;
            if (NumberUtils.isNotNullOrZero(alarmVO.getAlarmId())) {
                queryBean = vcAlarmService.getAlarmByalarmId(alarmVO.getAlarmId(), 1L);
            } else if (NumberUtils.isNotNullOrZero(alarmVO.getUid())) {
                queryBean = vcAlarmService.getAlarmByUid(alarmVO.getUid(), 1L);
            }
            if (queryBean != null) {
                //关闭告警
                queryBean.setAlarmState(alarmVO.getAlarmState());
                queryBean.setDealTime(new Date());
                queryBean.setDealUid(userBasicFDB.getUid());
                VcAlarm alarm = vcAlarmService.saveAlarm(queryBean);

                tp.execute(new AlarmSendThread(roomService, alarm.getRid(), GlobalConstant.IMS_ALARM_CLOSE, alarm));
                //删除告警频道
                RoomBasic roomBasic = roomService.getRoomBasicByRid(queryBean.getRid());
                if (roomBasic != null) {
                    roomService.delRoomBasic(queryBean.getRid());
                    roomService.updateRoomBasicVersion(queryBean.getRid());
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    private VcAlarm convertAlarm(RoomBasic roomBasic, AlarmVO alarmVO) throws Exception {
        VcAlarm vcAlarm = new VcAlarm();
        BeanUtils.copyProperties(vcAlarm, alarmVO);
        vcAlarm.setPartyId(roomBasic.getPartyId());
        vcAlarm.setOrgCode(roomBasic.getOrgCode());
        vcAlarm.setOrgId(roomBasic.getOrgId());
        vcAlarm.setRid(roomBasic.getRid());
        vcAlarm.setAlarmType(1L);
        vcAlarm.setAlarmState(1L);
        vcAlarm.setState(1L);
        return vcAlarm;
    }

    private RoomBasic createRoom(List<UserBasic> userBasicListFDB, UserBasic userBasicFDB, AlarmVO alarmVO) throws Exception {
        RoomVO roomVO = new RoomVO();
        roomVO.setPartyId(userBasicFDB.getPartyId());
        roomVO.setOrgId(userBasicFDB.getOrgId());
        roomVO.setOrgCode(userBasicFDB.getOrgCode());
        roomVO.setUid(userBasicFDB.getUid());
        roomVO.setName(alarmVO.getRoomName());
        roomVO.setUids(getUidsList(userBasicListFDB));
        roomVO.setStyle(alarmVO.getRoomStyle());
        roomVO.setExpireType(1L);
        RoomBasic roomBasicFDB = roomService.createRoom2Member(roomVO);
        if (roomBasicFDB != null) {
            roomService.updateRoomBasicVersion(roomBasicFDB.getRid());

            if (!roomVO.getUids().isEmpty() && roomBasicFDB != null) {
                for (long uid : roomVO.getUids()) {
                    roomService.updateRoomMemberVersion(uid,roomBasicFDB.getRid());
                }
            }
        }
        return roomBasicFDB;
    }

    private List<Long> getUidsList(List<UserBasic> userBasicListFDB) {
        List<Long> uids = new ArrayList<>();
        for (UserBasic userBasic : userBasicListFDB) {
            uids.add(userBasic.getUid());
        }
        return uids;
    }
}
